import { shallowRef } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import icon from '~/assets/amapMarker.png'

/**
 * 初始化amap 在父组建的onMounted执行结束后才会进行赋值操作
 * @param nodeId dom元素的id用来设置地图容器id
 * @param aMapOptions 初始化地图配置项 aMapType 如果需要其他的类型的地图非map的就传参在aMapType 里面 例如热力图 参数改为 aMapType: 'HeatMap'
 * @param callback 在初始化地图后的回调函数
 * @returns 数组 0 new 之后的map对象 1 AMap构造函数 2 地图中所用到的标记icon
 */
export default function useAMap(
  nodeId: string,
  aMapOptions: Record<string, any> & { aMapType?: string },
  callback?: () => void
) {
  const map = shallowRef()
  const amap = shallowRef()
  const amapIcon = shallowRef()

  AMapLoader.load({
    key: '69826d8b560eb047de101d7fae9ff485', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.Polygon',
      'AMap.Scale',
      'AMap.HawkEye',
      'AMap.ToolBar',
      'AMap.ControlBar',
      'AMap.PlaceSearch',
      'AMap.DistrictSearch',
      'AMap.HeatMap',
      'AMap.3DTilesLayer',
      'AMap.IndoorMap',
      'AMap.MoveAnimation',
      'AMap.ElasticMarker',
      'AMap.MarkerCluster',
      'AMap.IndexCluster',
      'AMap.MouseTool',
      'AMap.BezierCurveEditor',
      'AMap.RectangleEditor',
      'AMap.CircleEditor',
      'AMap.EllipseEditor',
      'AMap.GeoJSON',
      'AMap.PolylineEditor',
      'AMap.PolygonEditor',
      'AMap.AutoComplete',
      'AMap.Driving',
      'AMap.Walking',
      'AMap.Riding',
      'AMap.Transfer',
      'AMap.Geocoder',
      'AMap.GraspRoad',
      'AMap.StationSearch',
      'AMap.LineSearch',
      'AMap.ArrivalRange',
      'AMap.CitySearch',
      'AMap.Geolocation',
      'AMap.Weather',
      'AMap.RangingTool'
    ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    Loca: {
      version: '2.0.0'
    }
  }).then((AMap) => {
    // var satellite = new AMap.TileLayer.Satellite();
    // var roadNet = new AMap.TileLayer.RoadNet();
    if (aMapOptions.aMapType && AMap[aMapOptions.aMapType]) {
      map.value = new AMap[aMapOptions.aMapType](nodeId, {
        ...aMapOptions,
        layers: [
          // roadNet
          // AMap.createDefaultLayer()
          // AMap.TileLayer.Satellite(),
          // AMap.TileLayer.RoadNet()
        ]
      })
    } else {
      map.value = new AMap.Map(nodeId, { ...aMapOptions, layers: [AMap.createDefaultLayer()] })
    }
    amap.value = AMap
    amapIcon.value = new AMap.Icon({
      size: new AMap.Size(24, 24),
      imageSize: new AMap.Size(24, 24),
      image: icon
    })
    callback?.()
  })

  return [map, amap, amapIcon]
}
